package com.github.springboot.exception;

import com.github.springboot.common.Response;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.NativeWebRequest;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by kjtang on 2018/1/18.
 * 全局异常处理
 */
@ControllerAdvice
public class ApplicationExceptionHandler {

    @ExceptionHandler({ Exception.class })
    public @ResponseBody Response processControllerException(NativeWebRequest request, Exception e) {
        Response response = new Response(Response.FAIL);
        if (e instanceof ErrorRCodeException) {
            ErrorRCodeException exception = (ErrorRCodeException)e;
            response.setMsg(exception.getMessage());
            response.setCode(exception.getRcode());
        }else if(e instanceof MethodArgumentNotValidException){
            MethodArgumentNotValidException exception = (MethodArgumentNotValidException)e;
            //按需重新封装需要返回的错误信息
            List<Map> listMapError = new ArrayList<>();
            //解析原错误信息，封装后返回，此处返回非法的字段名称，原始值，错误信息
            for (FieldError error : exception.getBindingResult().getFieldErrors()) {
                  Map errorMap = new HashMap();
                  errorMap.put("defaultMessage",error.getDefaultMessage());
                  errorMap.put("field",error.getField());
                  errorMap.put("rejectedValue",error.getRejectedValue());
                  listMapError.add(errorMap);
           }
           response.setErrors(listMapError);
        }else if(e instanceof HttpMessageNotReadableException ||e instanceof HttpMessageNotWritableException){
            response.setMsg("参数格式错误，需为正确的JSON格式");
        }else{
            response.setMsg(e.getMessage());
        }
        return response;
    }
}
